from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
# Create your views here.
from app import models


# 验证登录装饰器
def check_login(func):
    def warppr(request, *args, **kwargs):
        is_login = request.session.get('IS_LOGIN', False)
        if is_login:
            return func(request, *args, **kwargs)
        else:
            return HttpResponseRedirect("/login")

    return warppr


# 购物车
@check_login
def cart_view(request):
    if request.method == "POST":
        uid = request.session['user_id']
        good_id = request.POST.get("good_id")
        num = request.POST.get('num')
        cart = models.Cart.objects.filter(user__name=uid, goods__id=good_id).first()
        if cart:
            cart.num = cart.num + int(num)
            cart.save()
        else:
            cart = models.Cart.objects.create(
                user_id=uid,
                num=int(num)
            )
            good = models.Goods.objects.get(id=good_id)
            cart.goods.add(good)
        return HttpResponse({"status": 1, "msg": "添加购物车成功"})
    elif request.method == "GET":
        uid = request.session['user_id']
        list = []
        cart_list = models.Cart.objects.filter(user_id=uid)
        total_price = 0
        count = 0
        for item in cart_list:
            goods = item.goods.field()
            goodDic = {}
            goodDic["good_name"] = goods.good_name
            goodDic["price"] = goods.price
            goodDic["unit"] = goods.unit
            goodDic["img_url"] = goods.img_url
            goodDic["num"] = item.num
            total = item.num * goods.price
            goodDic["total_price"] = total
            count += 1
            total_price += total
            list.append(goodDic)
        return render(request, 'cart.html', {"list": list, "total_price": total_price, "count": count,
                                             "user_name": request.session.get('user_name', None)})
    else:
        return render(request, 'cart.html', {'user_name': request.sessiopn.grt('user_name', None)})


# 登录
def login_view(request):
    if request.method == "POST":
        user_name = request.POST.get('user_name', ' ')
        pass_word = request.POST.get('pwd', ' ')
        user = models.User.objects.get(user_name=user_name, pwd=pass_word)
        if user:
            if pass_word == user.pwd:
                request.session['IS_LOGIN'] = True
                request.session['user_name'] = user_name
                request.session['user_id'] = user.id
                return render(request, 'index.html', {'user_name': user_name})
            else:
                return render(request, 'login.html', {'error': '用户名或密码错误！'})
        else:
            return render(request, 'login.html', {'error': '用户名不存在！'})
    elif request.method == "GET":
        return render(request, 'login.html')
    else:
        return render(request, 'login.html')


# 首页
def index_view(request):
    if request.method == "GET":
        goods_type = models.Type.objects.all()
        goods_dict = {}
        for type in goods_type:
            goods_list = models.Goods.objects.filter(type__id=type.id)[:4]
            goods_dict[type.type_name] = goods_list
        print(goods_dict)
        return render(request, 'index.html', {"goods_list": goods_dict, 'goods_type': goods_type})


# 上平详情
def goodDetail(request, id):
    goods_detail = models.Goods.objects.get(id=id)
    return render(request, 'detail.html', {"good": goods_detail, 'user_name': request.session.get('user_name', None)})


# 退出登录
def loginOut(request):
    request.session.flush()
    return render(request, 'login.html')


# 注册
def register_view(request):
    if request.method == 'GET':
        return render(request, 'register.html')
    elif request.method == 'POST':
        user_name = request.POST.get('user_name', ' ')
        pass_word_1 = request.POST.get('pwd', ' ')
        pass_word_2 = request.POST.get('cpwd', ' ')
        phone = request.POST.get('phone', ' ')
        if models.User.objects.filter(user_name=user_name):
            return render(request, 'register.html', {'error': '用户已存在'})
        if pass_word_1 != pass_word_2:
            return render(request, 'register.html', {'error': '两次密码请输入一致！'})
        user = models.User()
        user.user_name = user_name
        user.pwd = pass_word_1
        user.phone = phone
        user.save()
        return render(request, 'login.html')
    else:
        return render(request, 'register.html')


def index_views(request):
    return render(request, 'index.html')
